<?php
namespace Admin\Controller;
use Think\Controller;
class AuthController extends CommonController
{	
	
	public $auth ;


	public function _initialize(){
		// $this->role = D('role as a');
		$this->auth = D('auth');
		// $this->role_auth = D('role_auth');
	}

	public function showlist(){

		
		$auths = $this->auth->select();//查找权限列表
		$list = $this->get_list($auths);

		

		// $this->assign('role_auth',$role_auth);
		$this->assign('list',$list);
		// $this->assign('roles',$roles);
		$this->display();
	}

	public function append(){
		$auths = $this->auth->select();//查找权限列表
		$list = $this->get_list($auths);//权限列表无极分类

		

		

		if(IS_POST){

			



			$info = ['code' => 0 , 'info' => '' , 'statu' => 'error'];
			
			// var_dump($data);die;
			//遍历添加权限
			if(!$this->auth->create()){
				$info['info'] = $this->auth->getError();
				$this->ajaxReturn($info);
			}else{
				$auth = $this->auth->add();
				if($auth){

					$info['code'] = 1;
					$info['info'] = '添加成功';
					$info['status'] = 'success';
				}

				$this->ajaxReturn($info);
			}
			
			

			
		}
		
		$this->assign('list',$list);
		$this->display();
	}

	public function edit(){

		$auths = $this->auth->select();//查找权限列表
		$list = $this->get_list($auths);//权限列表无极分类

		$auth_id = I('get.auth_id');
		$auth = $this->auth->where(['auth_id' => $auth_id])->find();
		if(IS_POST){
			$info = ['code' => 0 , 'info' => '' , 'status' => 'error'];
			

			

			if(!$this->auth->create()){
				$info['info'] = $this->auth->getError();
				$this->ajaxReturn($info);
			}else{
				//删除减少的权限
				$result = $this->auth->save();
				if($result){
					$info['code'] = 1;
					$info['info'] = '修改成功';
					$info['status'] = 'success';
					$this->ajaxReturn($info);
				}else{
					$info['info'] ='修改失败';
					$this->ajaxReturn($info); 
				}

			}
		}
		
		$this->assign('auth',$auth);
		$this->assign('list',$list);
		$this->display();
	}

	public function del(){
		if(IS_POST){
			$info = ['code' => 0 , 'info' => '' , 'status' => 'error'];
			$auth_id = I('post.auth_id');
			$where = ['auth_id'=>$auth_id];
			$chk_child = $this->auth->where(['pid'=>$auth_id])->find();
			if(!empty($chk_child)){
				$info['info'] = '存在子级权限无法删除';
				$this->ajaxReturn($info);
			}else{
				$result = $this->auth->where($where)->delete();
				if($result){
					
					$info['code'] = 1;
					$info['info'] = '删除成功';
					$info['status'] = 'success';
					$this->ajaxReturn($info);
	 			
				}else{
					$info['info'] = '删除失败';
					$this->ajaxReturn($info);
				}
			}
		}
	}

	public function get_list($array,$pid=0){
		$list = array();

		foreach($array as $vo){
			if($vo['pid'] == $pid){
				$child = $this->get_list($array,$vo['auth_id']);
				$vo['child'] = $child;
				$list[] = $vo;
			}
		}

		return $list;
	}

}
